#coding=utf-8
'''
Created on 2017-04-26

@author: sandy
'''
import logging
import time
from pycommon import RedisPool


class RedisDB(object):
    def __init__(self):
        self.dbp = None

    def start(self,host,port=6379,db=0,passwd=None,linkcount=3):
        self.linkcount = linkcount
        logging.info("Redis host=%s,port=%s,db=%s,passwd=%s",host,port,db,passwd)
        self.dbp = RedisPool.RedisConnectionPool(host = host,port = port,db = db,passwd = passwd,linkcount = linkcount)
        self.dbp.start()
    
    def stop(self):
        self.dbp.stop()
        self.dbp = None

    def hashIndex(self, uid):
        return uid % self.linkcount

    def execute(self, conindex, ctx, cmd, params, func, options={}):
        self.dbp.execute(conindex, ctx, cmd, params, func, options)

    def addUserSession(self,uid,session):
        def cmd(con):
            pipe = con.pipeline()
            pipe.hset(uid,"session",session)
            pipe.expire(uid, 86400 * 30)
            return pipe.execute()
            pass
        def finish(ctx,error,result):
            uid,session = ctx
            if error:
                logging.error(u'addUserSession(), uid=%d, error=%s', uid, unicode(error))
                return
            else:
                logging.debug("addUserSession uid=%d session=%s sucess",uid,session)
            pass
        ctx = (uid,session)
        params = (uid,session)
        self.execute(self.hashIndex(uid),ctx,cmd,params,finish)

    def getUserSession(self,uid,cbk):
        def cmd(con):
            pipe = con.pipeline()
            pipe.hget(uid,"session")
            return pipe.execute()[0]
            pass
        def finish(ctx,error,result):
            if error:
                logging.error(u'getUserSession(), uid=%d, error=%s', uid, unicode(error))
            else:
                logging.debug("getUserSession() uid=%d redisSession=%s",uid,result)
                cbk(result)
            pass
        ctx = None
        params = None
        self.execute(self.hashIndex(uid),ctx,cmd,params,finish)

    def addSucessFunc(self,key,design,num):
        def cmd(con):
            pipe = con.pipeline()
            pipe.hset(key,"design",design)
            pipe.hset(key,"num",num)
            pipe.expire(key, 86400 * 30)
            return pipe.execute()
            pass
        def finish(ctx,error,result):
            key,design,num = ctx
            if error:
                logging.error(u'addSucessFunc(), key=%s, error=%s', key, unicode(error))
                return
            else:
                logging.debug("addSucessFunc key=%s design=%s num=%d",key,design,num)
            pass
        ctx = (key,design,num)
        params = (key,design,num)
        self.execute(self.hashIndex(int(time.time())),ctx,cmd,params,finish)

instance = RedisDB()

if __name__ == '__main__':
    pass
